/*
*	用class="successPart"和class="normalPart"两部分的隐藏和显示来控制“输入手机号”还是“提示结果”，
*   成功或失败的消息由submit中的函数控制，此消息应该是ajax返回的。
*
*
*/
var validate =  function(str){
	var phoneRules = /^1[3|4|5|8]\d{9}$/;
	return phoneRules.test(str);
}

var submit = function(str){
	//ajax


localStorage["phone"] = str;
$('#debug').load('/ajax.php?ac=get_hongbao&mobile='+str,function(data){ 
var obj = eval("(" + data + ")");
if(obj.status=='0'){
$('#rtje1').html(obj.je);
		var msg = '您已领取红包啦~';
		$(".normalPart").hide();
		$("#successPart").hide();
		$("#successPart1").show();
		$("#successPhoneNumer1").html(str);
		$("#result1").html(msg) 
}
if(obj.status=='1'){
//success:
$('#rtje').html(obj.je);
		var msg = '成功领取红包！';
		$(".normalPart").hide();
		$("#successPart").show();
		$("#successPhoneNumer").html(str);
		$("#result").html(msg)	
}
});
}

var init = function(){
	var submitBtn = $("#receiveBtn");
	var phoneText = $("#phoneText");
	
	//先判断是否已经领取过红包，可以获取到手机号
	if(validate(localStorage["phone"])){
		$("#phoneNum").text(localStorage["phone"]);
		phoneText.hide();
		$("#hasPhone").show();
		submitBtn.removeClass("disable").addClass("clickable");
		
		
		$(".change").bind("click",function(){
			delete localStorage["phone"];
			phoneText.show();
			$("#hasPhone").hide();
			submitBtn.removeClass("clickable").addClass("disable");
		})
	}
	

	phoneText.on("change",function(e){
		var isValid = validate(phoneText.val());
		if(isValid){
			submitBtn.removeClass("disable").addClass("clickable");
		}else{
			submitBtn.removeClass("clickable").addClass("disable");
		}

		var k = window.event ? e.keyCode : e.which;
	    if (k == 13) {
	    	if(validate(phoneText.val()) && submitBtn.hasClass("clickable")){
				submit(phoneText.val());
			}else{
				phoneText.focus();
			}
	    }
	});

	submitBtn.on("click",function(e){
		e.preventDefault();
		var phoneNum = localStorage["phone"];
		if(validate(phoneText.val())&&submitBtn.hasClass("clickable")){
			submit(phoneText.val());
		}else if(validate(phoneNum)){
			submit(phoneNum);
		}else{
			phoneText.focus();
		}
	})

	$("#ruleLink").on("click",function(){
		$.pgwModal({
		    target: '#modalContent',
		    title: '红包使用规则',
		});
	})
}

$(document).ready(function(){
	init();
});